package com.jiangruan.javaproject.request;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author:yuhongwei
 * @email:yuhongwei@1000phone.com
 * @desc: 该类用于封装提供网络请求的功能代码，用于发起网络请求，并将
 * 网络的数据进行返回
 * @datetime: 2021/12/4 9:29
 */
public class HttpUtils {

    /**
     * 该函数用于实现get请求，并将请求的结果进行返回
     * @param path 请求的资源路径
     * @return 请求的结果
     */
    public static String get(String path) {
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;

        String line = "";//最开始空行
        String result = "";//每次读取到以后都要累计起来的读取结果
        try {
            //Union Resource Location 统一资源定位
            URL url = new URL(path);
            URLConnection conn = url.openConnection();
            //进行连接
            conn.connect();

            inputStream = conn.getInputStream();

            //字符流：按行读
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);

            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭读取流
            try {
                if (reader != null) {
                    reader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
